<template>
  <tm-app :followTheme="true">
    <tm-navbar title="签到" :followTheme="true" :hideHome="true"> </tm-navbar>
    <tm-sheet :margin="[20]" :padding="[40]" :transprent="true">
      <view class="flex flex-row flex-row-center-between">
        <tm-text :font-size="40" color="#fff">每日签到领现金</tm-text>
        <tm-text
          :font-size="28"
          color="#fff"
          linearDeep="accent"
          linear="right"
          @click="state.showSignRule = true"
        >
          签到规则
        </tm-text>
      </view>

      <tm-text
        :font-size="28"
        color="#fff"
        _class="my-n5"
        :label="`连续签到${state.signRecord.accSignNumber}天，奖励金额${
          state.signRecord.accSignMoney || '-'
        }元`"
      >
      </tm-text>

      <view class="pa-n5 round-7 my-n5" style="background-color: #fff">
        <tm-calendar-view
          :dateStyle="state.signRecord.accSignDay"
          :multiple="false"
          :hideButton="true"
          color="green"
          model="day"
          @change="dateChange"
        ></tm-calendar-view>
        <tm-button
          :margin="[30]"
          :round="10"
          block
          :follow-theme="true"
          :loading="state.loading"
          label="block"
          linearDeep="accent"
          linear="right"
          @click="startAdd"
          :label="!state.status ? '立即签到' : '今日已签，隔日再来'"
        >
        </tm-button>
        <tm-button
          :margin="[30]"
          :round="10"
          block
          outlined
          :follow-theme="true"
          label="block"
          linearDeep="accent"
          linear="right"
          @click="getInviteCode"
        >
          分享朋友赚现金
        </tm-button>
      </view>
      <view class="pa-n5 round-7 my-n5" style="background-color: #fff">
        <view class="grid-3">
          <view v-for="(item, index) in state.signLevel" :key="index">
            <tm-sheet
              :follow-theme="true"
              :padding="[30, 20]"
              :margin="[0]"
              linearDeep="accent"
              linear="right"
              :round="5"
              _class="fulled"
            >
              <tm-text :font-size="24">签到{{ item.accSignNumber }}天</tm-text>
              <view class="flex flex-row flex-row-center-center mt-n3">
                <tm-text :font-size="40" _class="mr-n3">{{
                  item.accSignMoney
                }}</tm-text>
                <tm-text :font-size="24">元</tm-text>
              </view>
            </tm-sheet>
          </view>
        </view>
      </view>
    </tm-sheet>

    <tm-overlay v-model:show="state.showSignRule" contentAnimation>
      <view @click.stop="">
        <tm-sheet
          :width="600"
          :follow-theme="true"
          :round="5"
          linearDeep="accent"
          linear="bottom"
          _style="overflow-y:scroll"
        >
          <view class="flex flex-row flex-row-center-center my-n5">
            <tm-text label="签到规则" :font-size="40"></tm-text>
          </view>
          <scroll-view :scroll-top="0" :scroll-y="true" style="height: 500px">
            <tm-text
              :label="item.sysValue"
              _class="mt-n5"
              v-for="item in state.signRule"
              :key="item.id"
            ></tm-text>
          </scroll-view>
        </tm-sheet>
      </view>
    </tm-overlay>
  </tm-app>
</template>

<script setup>
import { onLoad, onReady } from "@dcloudio/uni-app";
import { reactive, watch, nextTick } from "vue";
import dayjs from "dayjs";
import { tmplIds } from "@/config";
import {
  signStatusApi,
  signRegulationApi,
  signLevelListApi,
  signRecordListApi,
  signApi,
} from "@/api";

onReady(() => {
  // 在页面onLoad回调事件中创建激励视频广告实例
  if (uni.createRewardedVideoAd) {
    state.videoAd = uni.createRewardedVideoAd({
      adUnitId: "adunit-0af7b9860693fa33",
    });
    state.videoAd.onLoad(() => {});
    state.videoAd.onError((err) => {});
    state.videoAd.onClose((res) => {
      state.addShowEnd = res.isEnded;
      if (!res.isEnded) {
        uni.showToast({
          icon: "error",
          title: "视频未播放完毕",
        });
      } else {
        startSign();
      }
    });
  }
});

const state = reactive({
  value: dayjs().format("YYYY-MM"),
  showSignRule: false,
  loading: false,
  // 广告是否看完
  addShowEnd: false,
  // 广告实例
  videoAd: null,
  // 当日签到状态
  status: null,
  signRule: [],
  signLevel: [],
  signRecord: {
    // 签到天数列表
    accSignDay: [],
    // 赚取的金额
    accSignMoney: null,
    // 签到天数
    accSignNumber: 0,
  },
});

const startAdd = () => {
  // 用户触发广告后，显示激励视频广告
  if (!state.addShowEnd && state.videoAd) {
    state.videoAd.show().catch(() => {
      // 失败重试
      state.videoAd
        .load()
        .then(() => state.videoAd.show())
        .catch((err) => {
          console.log("激励视频 广告显示失败");
        });
    });
  } else {
    startSign();
  }
};

watch(
  () => state.value,
  async (date) => {
    state.signRecord = await signRecordListApi({
      month: date,
    });
    if (state.signRecord.accSignDay.length) {
      state.signRecord.accSignDay = state.signRecord.accSignDay.map((item) => {
        return {
          text: false, //浅色背景。
          color: "indigo", //主题色.
          extra: "签到", //额外的内容，在日期下方显示的文本。
          date: dayjs(item.signDateTime).format("YYYY-MM-DD"),
        };
      });
    }
  },
  {
    immediate: true,
  }
);

onLoad(() => {
  // 签到状态
  signStatusApi().then((res) => {
    state.status = res;
  });
  // 规则
  signRegulationApi().then((res) => {
    state.signRule = res;
  });
  //签到奖励
  signLevelListApi().then((res) => {
    state.signLevel = res.sort((a, b) => a.accSignNumber - b.accSignNumber);
  });
});

const dateChange = (e) => {
  state.value = dayjs(e).format("YYYY-MM");
};

const startSign = async () => {
  if (state.status) {
    uni.showToast({
      icon: "error",
      title: "今日已签",
    });
    return;
  }
  state.loading = true;
  await signApi();
  uni.showModal({
    title: "签到成功",
    content: "开启订阅即可签到提醒",
    success: function (res) {
      if (res.confirm) {
        openAuth();
      }
    },
  });
  signStatusApi().then((res) => {
    state.status = res;
  });
  state.value = "";
  await nextTick();
  state.value = dayjs().format("YYYY-MM");
  state.loading = false;
};

const openAuth = () => {
  uni.requestSubscribeMessage({
    tmplIds,
    success: (res) => {
      console.log(res);
    },
    fail: (error) => {
      console.log(error);
    },
  });
};

const getInviteCode = async () => {
  uni.navigateTo({
    url: "/homePages/subs/sign-invite-code",
  });
};
</script>

<style scoped>
.grid-3 {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  min-height: 100rpx;
}
</style>
